import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ty_smart_watch/ble/ble_util.dart';
import 'package:ty_smart_watch/ble/connected_device_controller.dart';
import 'package:ty_smart_watch/common/function_id.dart';
import 'package:ty_smart_watch/db/device_in_db_controller.dart';
import 'package:ty_smart_watch/page/device/device_info_controller.dart';
import 'package:ty_smart_watch/utils/Log.dart';

import '../../common/images_url.dart';
import '../../route/routes.dart';

class ConnectedDeviceListPage extends StatefulWidget {
  const ConnectedDeviceListPage({super.key});

  @override
  State<StatefulWidget> createState() => _ConnectedDeviceListPage();
}

class _ConnectedDeviceListPage extends State<ConnectedDeviceListPage> {
  DeviceInDbController dbController = Get.find();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("设备列表"),
        // centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () {
            Get.back();
          },
        ),
        actions: [
          IconButton(
              onPressed: () {
                Get.toNamed(Routes.scanDevicePage);
              },
              icon: const Icon(
                Icons.add_circle_outline_outlined,
                color: Colors.red,
              ))
        ],
      ),
      body: Obx(
        () => ListView.builder(
          itemCount: dbController.deviceList.value.length + 1,
          // itemCount: controller.deviceListList.length,
          // scrollDirection: Axis.vertical,
          itemBuilder: (context, index) {
            if (index < dbController.deviceList.value.length) {
              return GestureDetector(
                  onTap: () {
                    // 在此处添加你希望执行的点击事件处理逻辑
                    print('Clicked on $index');
                  },
                  child: DeviceItem(
                      name: dbController.deviceList.value[index]["name"],
                      mac: dbController.deviceList.value[index]["address"]));
            } else {
              return GestureDetector(onTap: () {}, child: const AddNewDevice());
            }
          },
        ),
      ),
    );
  }
}

class DeviceItem extends StatelessWidget {
  var smallTextStyle = const TextStyle(fontSize: 10);

  // DiscoveredDevice device;
  String name;
  String mac;

  DeviceItem({super.key, required this.name, required this.mac});

  DeviceInfoController deviceInfoController = Get.find();

  bool getConnectState() {
    DeviceController controller = Get.find();
    bool connectState = controller.connectDeviceMap.value[mac] != null;
    return connectState;
  }

  String getConnectText(bool connectState) {
    if (connectState) {
      return "已连接";
    } else {
      return "未连接";
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (getConnectState()) {
          Get.toNamed(Routes.watchDetailPage, arguments: {"mac": mac});
        } else {
          Log.d("卡片 - 设备未连接");
        }
      },
      child: Container(
        decoration: const BoxDecoration(
          //圆角半径
          borderRadius: BorderRadius.all(Radius.circular(12.0)),

          //背景图片
          image: DecorationImage(image: AssetImage(SPORT_DASHBOARD_BACKROUND), fit: BoxFit.fill),
        ),
        // child: Center(
        child: Container(
          padding: const EdgeInsets.all(30),
          child: Row(
            children: [
              Image.asset(ICON_WATHC_STYLE_1, width: 60, height: 60),
              const SizedBox(width: 10),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(name),
                  Row(
                    children: [
                      Text(getConnectText(getConnectState()), style: smallTextStyle),
                      const SizedBox(width: 4),
                      Text("|", style: smallTextStyle),
                      const SizedBox(width: 4),
                      Obx(
                        () => Text(deviceInfoController.battery.value, style: smallTextStyle),
                      ),
                    ],
                  ),
                  GestureDetector(
                    onTap: () {
                      _syncDeviceInfo();
                    },
                    child: Container(
                      margin: const EdgeInsets.only(top: 6),
                      padding: const EdgeInsets.fromLTRB(16, 4, 16, 4),
                      decoration: const BoxDecoration(
                        //圆角半径
                        borderRadius: BorderRadius.all(Radius.circular(50.0)),
                        color: Color.fromARGB(255, 255, 229, 202),
                      ),
                      child: const Text("同步",
                          style: TextStyle(
                              fontSize: 10,
                              fontWeight: FontWeight.w600,
                              color: Color.fromARGB(255, 206, 62, 0))),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  ///同步实时数据 0x0301
  _syncDeviceInfo() {
    if (getConnectState()) {
      BleUtil.writeBleData(mac, BleUtil.makeWriteData(functionId: REAL_TIME_DATA));
    }else{
      Log.d("同步 - 设备未连接");
    }
  }
}

///添加新设备卡片
class AddNewDevice extends StatelessWidget {
  const AddNewDevice({super.key});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Get.toNamed(Routes.scanDevicePage);
      },
      child: Container(
        height: 122,
        width: double.infinity,
        decoration: const BoxDecoration(
          //圆角半径
          borderRadius: BorderRadius.all(Radius.circular(12.0)),
          //背景图片
          image: DecorationImage(image: AssetImage(SPORT_DASHBOARD_BACKROUND), fit: BoxFit.fill),
        ),
        child: const Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.add_circle_outline_outlined,
                color: Color.fromARGB(255, 213, 213, 213), size: 60),
            Text("添加新设备", style: TextStyle(color: Color.fromARGB(255, 213, 213, 213)))
          ],
        ),
      ),
    );
  }
}
